// pages/goods/index.js
const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsId: '',
        goodsInfo: {},
        ipInfo: {},
        seriesInfo: {},
        productInfo: {},
        sellerInfo: {},
        isCollected: false,
        isSeller: false,
        isCollecting: false,
        collectCount: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options);
        if (options.goodsId) {
            this.setData({
                goodsId: options.goodsId
            });
            this.loadGoodsDetail();
            this.checkUserCollection();
            this.getGoodsCollectCount()
        } else {
            wx.showToast({
                title: '参数错误',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            });
        }
    },
    onShow() {
        this.loadGoodsDetail();
        this.checkUserCollection();
        this.getGoodsCollectCount()
    },
    // 加载商品详情
    loadGoodsDetail() {
        const {
            goodsId
        } = this.data;

        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        // 并发请求多个数据
        Promise.all([
                // 获取商品信息
                db.collection('blindbox_goods').doc(goodsId).get(),

            ])
            .then(results => {
                const [goodsRes] = results;
                console.log(goodsRes);
                if (!goodsRes.data) {
                    throw new Error('商品不存在');
                }
                const goodsInfo = goodsRes.data;
                let arr = goodsInfo.goodsImage.split(',')
                goodsInfo.images = arr
                goodsInfo.releaseTime = goodsInfo.releaseDate

                // // 检查当前用户是否是卖家
                const userInfo = wx.getStorageSync('userInfo');
                const currentUserId = userInfo._id;
                const isSeller = currentUserId === goodsInfo.sellerId;
                this.setData({
                    goodsInfo,
                    isSeller
                });
                // 获取卖家信息
                db.collection('users').doc(goodsInfo.sellerId || '').get().then(res => {
                    const sellerInfo = res.data
                    this.setData({
                        sellerInfo
                    });
                }).catch(err => {
                    console.error('获取卖家信息失败', err);
                });
                // 设置导航栏标题
                wx.setNavigationBarTitle({
                    title: goodsInfo.goodsName
                });
            })
            .catch(err => {
                console.error('加载商品详情失败:', err);
                wx.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });
            })
            .finally(() => {
                wx.hideLoading();
            });
    },
    // 获取商品收藏数
    getGoodsCollectCount: function () {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        wx.cloud.callFunction({
            name: 'getGoodsCollectCount',
            data: {
                goodsId: this.data.goodsId
            }
        }).then(res => {
            console.log(res);
            wx.hideLoading();
            if (res.result.success) {
                this.setData({
                    collectCount: res.result.count
                });
            } else {
                wx.showToast({
                    title: '获取收藏数失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('获取收藏数失败', err);
            wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
            });
        });
    },
    // 检查用户是否已收藏
    checkUserCollection() {
        const {
            goodsId
        } = this.data;
        const userInfo = wx.getStorageSync('userInfo');
        const currentUserId = userInfo._id;
        if (!currentUserId) return;

        db.collection('user_collections')
            .where({
                user_id: currentUserId,
                item_id: goodsId
            })
            .get()
            .then(res => {
                this.setData({
                    isCollected: res.data.length > 0
                });
            })
            .catch(err => {
                console.error('检查收藏状态失败:', err);
            });
    },

    // 收藏/取消收藏商品
    toggleCollect() {
        const {
            goodsId,
            isCollected,
            collectCount
        } = this.data;
        const userInfo = wx.getStorageSync('userInfo');
        const userId = userInfo._id;
        this.setData({
            isCollecting: true
        });

        if (isCollected) {
            // 取消收藏
            wx.cloud.callFunction({
                name: 'updateCollection',
                data: {
                    action: 'remove',
                    userId,
                    goodsId
                }
            }).then(res => {
                console.log(res);
                if (res.result.success) {
                    this.setData({
                        isCollected: false,
                        collectCount: collectCount - 1 // 前端直接更新收藏数
                    });
                    wx.showToast({
                        title: '已取消收藏',
                        icon: 'none'
                    });
                } else {
                    wx.showToast({
                        title: res.result.message || '取消收藏失败',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                console.error('取消收藏失败:', err);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            }).finally(() => {
                this.setData({
                    isCollecting: false
                });
            });
        } else {
            // 添加收藏
            wx.cloud.callFunction({
                name: 'updateCollection',
                data: {
                    action: 'add',
                    userId,
                    goodsId
                }
            }).then(res => {
                console.log(res);
                if (res.result.success) {
                    this.setData({
                        isCollected: true,
                        collectCount: collectCount + 1 // 前端直接更新收藏数
                    });
                    wx.showToast({
                        title: '收藏成功',
                        icon: 'none'
                    });
                } else {
                    wx.showToast({
                        title: res.result.message || '收藏失败',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                console.error('收藏失败:', err);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            }).finally(() => {
                this.setData({
                    isCollecting: false
                });
            });
        }
    },

    // 跳转到购买页面
    navigateToBuy() {
        const isLoggedIn = wx.getStorageSync('isLoggedIn');
        if (!isLoggedIn) {
            wx.navigateTo({
                url: '/pages/login/login'
            });
            return;
        }

        const {
            goodsId,
            isSeller,
            goodsInfo
        } = this.data;

        if (isSeller) {
            wx.showToast({
                title: '不能购买自己的商品',
                icon: 'none'
            });
            return;
        }

        if (goodsInfo.status === false) {
            wx.showToast({
                title: '该商品已卖出',
                icon: 'none'
            });
            return;
        }
        let data = JSON.stringify(goodsInfo)
        // 跳转到购买页面
        wx.navigateTo({
            url: `/pages/buy/buy?goodsId=${goodsId}&goodsInfo=${data}`
        });

    },

    // 跳转到对话页面
    navigateToChat() {

        const isLoggedIn = wx.getStorageSync('isLoggedIn');
        const userInfo = wx.getStorageSync('userInfo');
        const {
            goodsInfo,
            isSeller
        } = this.data;

        // 检查登录状态
        if (!isLoggedIn) {
            wx.navigateTo({
                url: '/pages/login/login'
            });
            return;
        }

        // 检查是否为自己的商品
        if (isSeller) {
            wx.showToast({
                title: '不能联系自己',
                icon: 'none'
            });
            return;
        }

        const sellerId = goodsInfo.sellerId;
        const currentUserId = userInfo._id;

        // 检查卖家ID是否存在
        if (!sellerId || sellerId === currentUserId) {
            wx.showToast({
                title: '卖家信息异常',
                icon: 'none'
            });
            return;
        }

        // 跳转到聊天页面，传递卖家ID
        wx.navigateTo({
            url: `/pages/chat/index?otherUserId=${sellerId}&goodsId=${this.data.goodsId}`
        });


    },


    takeOffline() {
        wx.showModal({
            title: '确认下架',
            content: '确定要下架该商品吗？',
            confirmColor: '#ff4d4f',
            success: (res) => {
                if (res.confirm) {
                    console.log(111);
                    const {
                        goodsId,
                        goodsInfo
                    } = this.data;
                    const sellerId = goodsInfo.sellerId;
                    wx.cloud.callFunction({
                        name: 'takeDownGoods',
                        data: {
                            goodsId: goodsId,
                            sellerId: sellerId
                        }
                    }).then(res => {
                        console.log(res);
                        if (res.result.success) {
                            wx.showToast({
                                title: '下架成功',
                                icon: 'none'
                            })
                            // 返回上一页并触发刷新
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 1,
                                    success: () => {
                                        // 触发上一页的刷新逻辑
                                        const pages = getCurrentPages();
                                        if (pages.length > 1) {
                                            const prevPage = pages[pages.length - 2];
                                            if (typeof prevPage.refreshData === 'function') {
                                                prevPage.refreshData();
                                            }
                                        }
                                    }
                                });
                            }, 1500);
                        } else {
                            wx.showToast({
                                title: res.result.message,
                                icon: 'none'
                            })
                        }
                    }).catch(err => {
                        console.error('下架失败:', err);
                        // 提供更具体的错误信息
                        if (err.errMsg.includes('permission denied')) {
                            wx.showToast({
                                title: '权限不足，无法下架',
                                icon: 'none'
                            });
                        } else if (err.errMsg.includes('document not found')) {
                            wx.showToast({
                                title: '商品不存在',
                                icon: 'none'
                            });
                        } else {
                            wx.showToast({
                                title: '下架失败，请重试',
                                icon: 'none'
                            });
                        }
                    })

                }
            }
        });
    },

    // 商品详情页中点击卖家信息
    goToSellerShop: function () {
        const sellerId = this.data.goodsInfo.sellerId;
        wx.navigateTo({
            url: `/pages/shop/shop?sellerId=${sellerId}&from=goods`
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})